/**
 * 
 */
package com.res.common.controller;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.res.simulator.handler.ConsumeAPIHandler;
import com.res.simulator.model.SavedAPIModel;
import com.res.simulator.view.ConsumerTemplateSaveView;
import com.res.system.common.SessionRegistry;
import com.sip.dbadapter.dao.exception.CustomException;

/**
 * @author Dhanushka Ariyasingha.
 */
@Controller
@SessionAttributes
public class TemplateSaveController extends BaseController {

    private static final Logger logger = Logger.getLogger(TemplateSaveController.class);

    @RequestMapping("/templatesavepopup")
    public String home(@ModelAttribute("SavedAPIModel") final SavedAPIModel model, final BindingResult result) {

        return "consumerssavelayout";
    }

    /**
     * Controller for main page save button action
     * 
     * @param model
     * @return
     */
    @RequestMapping(value = "/popup_save_template_window", method = RequestMethod.GET)
    public String popupSaveTemplateWindow(@ModelAttribute("SavedAPIModel") final SavedAPIModel model, final BindingResult result) {

        final String consumerString =  (String) getSession().getAttribute(SessionRegistry.CONSUMER_STRING_HIDDEN_VARIABLE);
        
        System.out.println("CONSUMER STRING : " + consumerString);
        model.setApiString(consumerString);
        
        return "redirect:templatesavepopup.htm";
    }

    @RequestMapping(value = "/save_consumer_string.htm", method = RequestMethod.GET)
    public String save(@ModelAttribute("SavedAPIModel") SavedAPIModel model) throws Exception {

        final String apiId = (String) getSession().getAttribute(SessionRegistry.API_ID_HIDDEN_VARIABLE);
        
        model.setApiId(Long.parseLong(apiId));

        // Data Saving Logic.
        final ConsumeAPIHandler handler = new ConsumeAPIHandler();
       try{
        ConsumerTemplateSaveView saveApiView = (ConsumerTemplateSaveView) handler.process(model);
       }catch(CustomException e){
           logger.info("CustomException Occurred============>"+e.getMessage());
       }

        return "redirect:genericapiexecutionmainpage.htm";
    }

    @RequestMapping(value = "/save_consumer_string.htm", method = RequestMethod.GET, params = "closeSaveDialog")
    public String closePopup(@ModelAttribute("SavedAPIModel") final SavedAPIModel model) throws Exception {

        return "redirect:genericapiexecutionmainpage.htm";
    }

}
